# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
# 导入智谱清言
import zhipuai
# 导入http.server库
import http.server
import socketserver
import urllib.parse
import json

class MyHttpRequestHandler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        # 解析查询字符串
        query = urllib.parse.urlparse(self.path).query
        params = urllib.parse.parse_qs(query)

        # 根据参数值返回响应
        if 'name' in params:
            name = params['name'][0]
            self.send_response(200)
            # self.send_header('Content-type', 'text/html')
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            # self.wfile.write("Hello, {0}!".format(name).encode('utf-8'))
            # self.wfile.write("Hello, {0}!".format(async_invoke_example(name)).encode('utf-8'))
            # self.wfile.write("{0}".format(invoke_example(name)).encode('GBK'))
            self.wfile.write("{0}".format(invoke_example(name)).encode('utf-8'))
        else:
            self.send_response(400)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            self.wfile.write(b'Missing parameter: name')


# 定义HTTP请求处理类
# class MyHttpRequestHandler(http.server.SimpleHTTPRequestHandler):
#     def do_GET(self):
#         # 处理GET请求
#         self.send_response(200)
#         self.send_header('Content-type', 'text/html')
#         self.end_headers()
#         self.wfile.write(b'Hello, World!')

# 创建HTTP服务器
def run():
    PORT = 8000
    Handler = MyHttpRequestHandler

    # 使用with语句创建HTTP服务器
    with socketserver.TCPServer(("", PORT), Handler) as httpd:
        print("Server started at localhost:{0}".format(PORT))
        httpd.serve_forever()



# your api key
zhipuai.api_key = "9952004b7f8ec1d4d4ec08c473bd88df.OAsuXy2HgQmciu9D"

def invoke_example():
    response = zhipuai.model_api.invoke(
        model="chatglm_turbo",
        # prompt=[{"role": "user", "content": "人工智能"}],
        # prompt=[{"role": "user", "content": "宁夏希望信息产业股份有限公司"}],
        prompt=[{"role": "user", "content": "使用java实现一个输出hello world"}],
        top_p=0.7,
        temperature=0.9,
    )
    print(response)

def invoke_example(name):
    response = zhipuai.model_api.invoke(
        model="chatglm_turbo",
        # prompt=[{"role": "user", "content": "人工智能"}],
        # prompt=[{"role": "user", "content": "宁夏希望信息产业股份有限公司"}],
        prompt=[{"role": "user", "content": name}],
        top_p=0.7,
        temperature=0.9,
    )
    print(response)
    # data = json.loads(response)
    # data = data['data']
    # print(f'Hi, {data}')
    # print(data)

    return response

def async_invoke_example():
    response = zhipuai.model_api.async_invoke(
        model="chatglm_turbo",
        prompt=[{"role": "user", "content": "人工智能"}],
        top_p=0.7,
        temperature=0.9,
    )
    print(response)

'''
  说明：
  add: 事件流开启
  error: 平台服务或者模型异常，响应的异常事件
  interrupted: 中断事件，例如：触发敏感词
  finish: 数据接收完毕，关闭事件流
'''

def sse_invoke_example():
    response = zhipuai.model_api.sse_invoke(
        model="chatglm_turbo",
        prompt=[{"role": "user", "content": "人工智能"}],
        top_p=0.7,
        temperature=0.9,
    )

    for event in response.events():
        if event.event == "add":
            print(event.data)
        elif event.event == "error" or event.event == "interrupted":
            print(event.data)
        elif event.event == "finish":
            print(event.data)
            print(event.meta)
        else:
            print(event.data)

def query_async_invoke_result_example():
    # response = zhipuai.model_api.query_async_invoke_result("your task_id")
    response = zhipuai.model_api.query_async_invoke_result("145216995107845308098027555225298500")
    print(response)

def print_hi(name):
    # Use a breakpoint in the code line below to debug your script.
    print(f'Hi, {name}')  # Press Ctrl+F8 to toggle the breakpoint.


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    # print_hi('PyCharm')
    # invoke_example()
    # async_invoke_example()
    # sse_invoke_example()
    # query_async_invoke_result_example()

    run()

# See PyCharm help at https://www.jetbrains.com/help/pycharm/
